home *** CD-ROM | disk | FTP | other *** search
/ Hacker's Secrets 4 / Hacker's Secrets 4.iso / internet / test-ran.c < prev    next >
C/C++ Source or Header  |  1995-11-23  |  2KB  |  83 lines

  1. /*
  2.  * test-rand.c - test the strength of rand()
  3.  * Time-stamp: <95/11/02 16:21:31 gildea>
  4.  *
  5.  * Determines how many unique MIT-MAGIC-COOKIE-1 keys are
  6.  * generated by rand() on this system.
  7.  *
  8.  * Written by Chris Hall, distributed by gildea@x.org
  9.  * This program is provided as is, without warranty of any kind.
  10.  */
  11.  
  12. #include <math.h>
  13. #include <stdio.h>
  14. #include <stdlib.h>
  15.  
  16. #ifdef RAND48
  17. #define rand lrand48
  18. #define srand srand48
  19. #endif
  20.  
  21. #ifdef RANDOM
  22. #define rand random
  23. #define srand srandom
  24. #endif
  25.  
  26. #define MASK 0xff
  27.  
  28. static int highest_bit = 8*sizeof(int) - 1;
  29.  
  30. int main()
  31. {
  32.    int    i, first, second, lb, ub;
  33.  
  34.    /*
  35.    **  find the lowest bit that matters
  36.    */
  37.  
  38.    for (i = 0; i <= highest_bit; i++)  {
  39.       srand (0);
  40.       first = rand ();
  41.       srand (1 << i);
  42.       second = rand ();
  43.  
  44.       if ((first & MASK) != (second & MASK))  {
  45.          lb = i;
  46.          printf ("lower bit = %d\n", i);
  47.          break;
  48.       }
  49.    }
  50.  
  51.    /*
  52.    **  find the highest bit which matters
  53.    */
  54.  
  55.    for (i = highest_bit; i >= 0; i--)  {
  56.       srand (0);
  57.       first = rand ();
  58.       srand (1 << i);
  59.       second = rand ();
  60.  
  61.       if ((first & MASK) != (second & MASK))  {
  62.          ub = i;
  63.          printf ("upper bit = %d\n", i);
  64.          break;
  65.       }
  66.    }
  67.  
  68.    printf ("There are %u possible cookies (%d bits).\n",
  69.            1 << (ub - lb + 1),
  70.            ub - lb + 1);
  71.    if (ub-lb+1 >= 24) {
  72.        printf("You have a relatively strong rand() function.\n");
  73.        /* but note that any rand() function is only as good as its inputs. */
  74.    }
  75.    else if (ub-lb+1 >= 16)
  76.        printf("You have a medium strength rand() function.\n");
  77.    else
  78.        printf("You have a weak rand() function.\n");
  79.  
  80.    return 0;
  81. }
  82.  
  83.